package com.shortchina.controller;

import com.shortchina.common.core.R;
import com.shortchina.common.exception.BaseException;
import com.shortchina.model.req.ApiGenerateReq;
import com.shortchina.model.vo.ShortUrlVo;
import com.shortchina.service.ApiAccessService;
import com.shortchina.service.URLService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.net.MalformedURLException;
import java.net.URL;

/**
 *  api接口
 * @author fc
 * @version 1.0
 * @data 2024/12/24 11:48 上午
 **/
@RestController
@RequestMapping("/api/v1")
public class ApiURLController {
    @Resource
    private ApiAccessService apiAccessService;
    @Resource
    private URLService urlService;

    @Value("${tshort.white_list:null}")
    private String whiteList;

    /**
     * 生成一个短链接
     * @param apiGenerateReq
     * @return
     * @throws BaseException
     */
    @PostMapping("/generate")
    public R<ShortUrlVo> generate(@Valid @RequestBody ApiGenerateReq apiGenerateReq) throws BaseException {
        String[] bmds = whiteList.split(",");
        //白名单判定
        try {
            URL url1 = new URL(apiGenerateReq.getUrl());
            String domain = url1.getHost();
            for (String bmd : bmds) {
                if (bmd.startsWith(domain)) {
                    break;
                }else{
                    return R.failed("不在白名单内");
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
          ShortUrlVo shortURL = urlService.generate(apiGenerateReq.getUrl(),apiGenerateReq.getValid());
          return R.ok(shortURL);
    }

    /**
     * 根据短链接的target解析原地址
     * @param target
     * @return
     * @throws BaseException
     */
    @GetMapping("/restore/{target}")
    public R<ShortUrlVo> restore(@PathVariable String target) throws BaseException {

        return R.ok(urlService.restoreByTarget(target));
    }

    /**
     * 根据完整的短链接解析原地址
     * @param url
     * @return
     * @throws BaseException
     */
    @GetMapping("/restoreFullUrl/{url}")
    public R<ShortUrlVo> restoreFullUrl(@PathVariable String url) throws BaseException {

        return R.ok(urlService.restoreByTarget(url));
    }

}
